package com.algrithom.array;

import java.util.Arrays;

/**
 * 566. 重塑矩阵
 * 
 * @author think
 */
public class Solution4 {
    
    public static void main(String[] args){
        //        int[][] mat = new int[][]{{1,2},{3,4}};
        int[][] mat = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16},{17,18,19,20}};
        Solution4 solution4 = new Solution4();
        int r = 100;
        int c = 110;
        int[][] result = solution4.matrixReshape(mat,r,c);
        for (int i = 0; i < result.length; i++) {
            System.out.println(Arrays.toString(result[i]));
        }
    }
    
    public int[][] matrixReshape(int[][] mat,int r,int c){
        int rowLen = mat.length;
        int colLen = mat[0].length;
        if (colLen * rowLen != r * c) {
            return mat;
        }
        int[][] result = new int[r][c];
        for (int i = 0; i < rowLen; i++) {
            for (int j = 0; j < colLen; j++) {
                int val = i * colLen + j;
                int rIndex = val / c;
                int cIndex = val % c;
                if (rIndex < r & cIndex < c) {
                    result[rIndex][cIndex] = mat[i][j];
                }
            }
        }
        return result;
    }
    
    public int[][] matrixReshape2(int[][] nums,int r,int c){
        int m = nums.length;
        int n = nums[0].length;
        if (m * n != r * c) {
            return nums;
        }
        
        int[][] ans = new int[r][c];
        for (int x = 0; x < m * n; ++x) {
            ans[x / c][x % c] = nums[x / n][x % n];
        }
        return ans;
    }
}
